package com.xinyu.web.testJdbcTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.xinyu.web.entity.User;

//使用JDBC模板实现正删改查
public class UserDaoImp extends JdbcDaoSupport implements UserDao{
	
/*	private JdbcTemplate jt;

	public JdbcTemplate getJt() {
		return jt;
	}

	public void setJt(JdbcTemplate jt) {
		this.jt = jt;
	}*/

	public void save(User u) {
		String sqlString = "insert into t_user values(null,?)";
		super.getJdbcTemplate().update(sqlString, u.getName());
	}

	public void del(Integer id) {
		String sql = "delete from t_user where id = ? ";
		super.getJdbcTemplate().update(sql, id);
	}

	public void update(User u) {
		String sql = "update  t_user set name = ? where id=? ";
		super.getJdbcTemplate().update(sql, u.getName(),u.getId());
	}

	public User getByID(Integer id) {
		String sqlString = "select * from t_user where id = ?";
		return	super.getJdbcTemplate().queryForObject(sqlString, new RowMapper<User>(){

				public User mapRow(ResultSet rs, int arg1)
						throws SQLException {
					User u = new User();
					u.setId(rs.getInt("id"));
					u.setName(rs.getString("name"));
					return u;
				}
				
			}, id);
	}

	public int getTotalCount() {
		
		String sql = "select count(*) from t_user  ";
		Integer queryForObject = super.getJdbcTemplate().queryForObject(sql, Integer.class);
		return queryForObject;
	}

	public List<User> getAll() {
		String sql = "select * from t_user  ";
		List<User> list =super.getJdbcTemplate().query(sql, new RowMapper<User>(){
			public User mapRow(ResultSet rs, int arg1) throws SQLException {
				User u = new User();
				u.setId(rs.getInt("id"));
				u.setName(rs.getString("name"));
				return u;
			}});
		return list;
	}
	
}
